package jdbc;

// 内置删除数据库数据

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class JdbcDelete {
    public static void main(String[] args) throws SQLException {
        // 创建数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/testbit?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("Xianmeng");

        // 建立连接
        Connection connection = dataSource.getConnection();

        // 构造SQL + 预处理
        Scanner in = new Scanner(System.in);
        System.out.println("输入你想要删除的名字：");
        String name = in.nextLine();

        String sql = "delete from students where name = ?"; // 删除某一行是delete
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1,name);

        // 执行sql
        int n = statement.executeUpdate();
        System.out.println("影响条数n=" + n);

        // 关闭释放
        statement.close();
        connection.close();

    }
}
